import { LanguageEnum } from '@/enums/appEnum'
import { useUserStore } from '@/store/modules/user'
import { router } from '@/router'
import type { AppRouteRecordRaw } from '@/router'
import type { MenuListType } from '@/types/menu.d'

// 动态注册路由
export function routerMatch(menuList: MenuListType[], roleRoutes: AppRouteRecordRaw[]) {
  console.log('开始路由匹配，菜单列表:', JSON.stringify(menuList, null, 2))
  console.log(
    '角色路由:',
    roleRoutes.map((route) => route.path)
  )

  const routesToAdd: AppRouteRecordRaw[] = []

  // 处理菜单列表
  menuList.forEach((item) => processMenuItem(item, roleRoutes, routesToAdd))

  console.log(
    '待添加的路由:',
    routesToAdd.map((route) => route.path)
  )

  // 添加路由到路由器
  routesToAdd.forEach((route) => {
    const { name } = route
    if (name && !router.hasRoute(name)) {
      console.log('添加路由:', route.path)
      router.addRoute(route)
    } else if (name) {
      console.log('路由已存在，跳过:', route.path)
    }
  })

  // 保存iframe路由
  saveIframeRoutes(routesToAdd)
}

function processMenuItem(
  item: MenuListType,
  roleRoutes: AppRouteRecordRaw[],
  routesToAdd: AppRouteRecordRaw[]
) {
  const { path, children = [], meta } = item
  const { title, title_en, icon, authList, keepAlive, isHide, isHideTab, isIframe, link } = meta

  console.log('处理菜单项:', path, '标题:', title)

  // 内嵌页面
  if (isIframe) {
    console.log('处理iframe菜单项:', path)
    routesToAdd.push({
      path: `/outside/iframe/${encodeURIComponent(title)}`,
      name: path,
      redirect: '',
      meta: {
        title,
        title_en,
        icon,
        keepAlive,
        link,
        isIframe,
        isHideTab,
        isHide
      }
    })
    return
  }

  // 标准化路径（确保以/开头）
  const normalizedPath = path.startsWith('/') ? path : `/${path}`
  console.log('标准化路径:', path, '=>', normalizedPath)

  // 先尝试直接匹配
  let matchingRoute = roleRoutes.find((route) => route.path === normalizedPath)
  console.log(
    '查找匹配路由:',
    normalizedPath,
    '结果:',
    matchingRoute ? matchingRoute.path : '未找到'
  )

  // 如果没有直接匹配，尝试其他可能的路径格式
  if (!matchingRoute) {
    // 尝试不以/开头的路径格式
    const altPath = normalizedPath.startsWith('/') ? normalizedPath.substring(1) : normalizedPath
    matchingRoute = roleRoutes.find((route) => route.path === altPath)
    console.log(
      '查找替代路径匹配:',
      altPath,
      '结果:',
      matchingRoute ? matchingRoute.path : '未找到'
    )
  }

  // 如果仍然没有匹配，尝试匹配父路由（去掉最后一个路径段）
  if (!matchingRoute) {
    // 对于子路由，尝试匹配其父路由
    const pathSegments = normalizedPath.split('/').filter((segment) => segment.length > 0)
    if (pathSegments.length > 1) {
      const parentPath = '/' + pathSegments.slice(0, -1).join('/')
      matchingRoute = roleRoutes.find((route) => route.path === parentPath)
      console.log(
        '查找父路由匹配:',
        parentPath,
        '结果:',
        matchingRoute ? matchingRoute.path : '未找到'
      )

      // 也尝试不以/开头的父路由格式
      if (!matchingRoute) {
        const altParentPath = parentPath.startsWith('/') ? parentPath.substring(1) : parentPath
        matchingRoute = roleRoutes.find((route) => route.path === altParentPath)
        console.log(
          '查找替代父路由匹配:',
          altParentPath,
          '结果:',
          matchingRoute ? matchingRoute.path : '未找到'
        )
      }
    }
  }

  if (matchingRoute) {
    matchingRoute.meta = {
      ...(matchingRoute.meta || {}),
      title,
      title_en,
      icon,
      authList,
      keepAlive,
      isHide,
      isHideTab
    }

    if (children.length > 0) {
      console.log('处理子菜单项:', normalizedPath, '子菜单数量:', children.length)
      children.forEach((child) =>
        processMenuItem(child, matchingRoute!.children || [], routesToAdd)
      )
    }

    // 检查是否已经添加过这个路由
    const alreadyAdded = routesToAdd.some((route) => route.path === matchingRoute!.path)
    if (!alreadyAdded) {
      routesToAdd.push(matchingRoute)
    }
  } else {
    // 匹配不上的路由
    console.error('【动态添加路由】找不到与路径匹配的路由:', normalizedPath)
  }
}

// 保存iframe路由
export const saveIframeRoutes = (routes: AppRouteRecordRaw[]) => {
  const iframeList = routes.filter((item) => item.meta?.isIframe)
  if (iframeList.length > 0) {
    sessionStorage.setItem('iframeRoutes', JSON.stringify(iframeList))
  }
}

// 菜单标题映射
const titlePropertyMap = {
  [LanguageEnum.ZH]: 'title',
  [LanguageEnum.EN]: 'title_en'
}

const getTitleProp = () => {
  return titlePropertyMap[useUserStore().language]
}

// 获取多语言菜单标题
export const getMenuTitle = (item: any) => {
  return item.meta[getTitleProp()]
}

// 获取 meta 多语言菜单标题
export const getMetaMenuTitle = (item: any) => {
  return item.meta[getTitleProp()]
}

// 获取标签页多语言标题
export const getWorkTabTitle = (item: any) => {
  return item[getTitleProp()]
}

// 打开链接
export const openLink = (link: string, isIframe: boolean = false) => {
  if (isIframe) {
    const iframeRoute = getIframeRoutes().find((route: any) => route.meta.link === link)
    if (iframeRoute?.path) {
      router.push({ path: iframeRoute.path })
    }
  } else {
    return window.open(link, '_blank')
  }
}

// 获取 iframe 路由
export const getIframeRoutes = () => {
  return JSON.parse(sessionStorage.getItem('iframeRoutes') || '[]')
}